package com.zw.yzk.kabu.adapter;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.target.Target;
import com.zw.yzk.kabu.R;
import com.zw.yzk.kabu.model.CosDetailsImageModel;
import com.zw.yzk.kabu.utils.PhoneUtils;
import com.zw.yzk.kabu.utils.QNImageUtils;
import com.zw.yzk.kabu.utils.StringUtils;
import com.zw.yzk.kabu.view.activity.HomePageActivity;
import com.zw.yzk.kabu.view.activity.TopicListActivity;
import com.zw.yzk.kabu.view.activity.imagedetails.ImageDetailsActivity;
import com.zw.yzk.kabu.view.activity.imagedetails.ImageListDetailsActivity;
import com.zw.yzk.kabu.view.activity.imagedetails.OriginalImageListDetailsActivity;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by zhanwei on 2017/1/15.
 */

public class CosDetailsImageAdapter extends RecyclerView.Adapter<CosDetailsImageAdapter.Holder> {

    private Context context;
    private List<CosDetailsImageModel> dataList;

    public CosDetailsImageAdapter(List<CosDetailsImageModel> list) {
        dataList = new ArrayList<>();
        if (list != null) {
            dataList.addAll(list);
        }
    }

    public void refresh(List<CosDetailsImageModel> list) {
        dataList.clear();
        if (list != null) {
            dataList.addAll(list);
        }
        notifyDataSetChanged();
    }

    private ArrayList<String> getImageList() {
        ArrayList list = new ArrayList();
        for (CosDetailsImageModel model : dataList) {
            list.add(model.getImageUrl());
        }
        return list;
    }

    @Override
    public Holder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (context == null) {
            context = parent.getContext();
        }
        View rootView = LayoutInflater.from(context).inflate(R.layout.recycler_item_cosplay_details_image, parent, false);
        return new Holder(rootView);
    }

    @Override
    public void onBindViewHolder(final Holder holder, int position) {
        final CosDetailsImageModel model = dataList.get(position);
        //设置文本样式
        SpannableString string = colorTextAndClickableWithPattern(
                model.getMessage(), StringUtils.DIVIDE_STRING_PATTERN1,
                ContextCompat.getColor(context, R.color.gold), context);
        SpannableString text = colorTextAndClickableWithPattern(
                string, StringUtils.DIVIDE_STRING_PATTERN2,
                ContextCompat.getColor(context, R.color.gold), context);
        holder.message.setText(text);
        holder.message.setMovementMethod(LinkMovementMethod.getInstance());
        holder.message.setHighlightColor(ContextCompat.getColor(context, R.color.transparent));
        if (TextUtils.isEmpty(model.getMessage())) {
            holder.message.setVisibility(View.GONE);
        }

        //按照图片比例将图片宽放大/缩小到屏幕宽度
        Glide.with(context)
                .load(QNImageUtils.getThumbnail(context, model.getImageUrl()))
                .asBitmap()
                .error(R.drawable.im_default)
                .into(new SimpleTarget<Bitmap>(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL) {
                    @Override
                    public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                        int imageWidth = resource.getWidth();
                        int imageHeight = resource.getHeight();
                        int screenWidth = PhoneUtils.getScreenWidth(context);
                        float scale = ((float) screenWidth) / imageWidth;
                        int height = (int) (scale * imageHeight);

                        ViewGroup.LayoutParams params = holder.image.getLayoutParams();
                        if (params == null) {
                            params = new ViewGroup.LayoutParams(screenWidth, height);
                        } else {
                            params.height = height;
                            params.width = screenWidth;
                        }
                        holder.image.setLayoutParams(params);
                        holder.image.setImageBitmap(resource);
                    }
                });

        holder.image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Rect rect = new Rect();
                holder.image.getGlobalVisibleRect(rect);
//                ImageListDetailsActivity.startImageListActivity(context, getImageList(), model.getImageUrl(), rect);
                OriginalImageListDetailsActivity.startOriginalImageListDetailsActivity(context, getImageList(), model.getImageUrl(), rect);
            }
        });
    }

    @Override
    public int getItemCount() {
        return dataList.size();
    }

    public static class Holder extends RecyclerView.ViewHolder {

        @Bind(R.id.message)
        TextView message;
        @Bind(R.id.image)
        ImageView image;

        public Holder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

    /**
     * 给特定格式文本着色并添加点击事件
     *
     * @param source  源文本
     * @param pattern 格式
     * @param color   颜色
     * @return SpannableString
     */
    private SpannableString colorTextAndClickableWithPattern(String source, String pattern, int color, Context context) {
        if (TextUtils.isEmpty(source)) {
            return new SpannableString("");
        }
        SpannableString spanText = new SpannableString(source);
        List<String> patternResult = StringUtils.divideString(source, pattern);
        String remainString = source;
        int realStart = 0;
        for (String str : patternResult) {
            realStart += remainString.indexOf(str);
            spanText.setSpan(new ClickSpan(context), realStart, realStart + str.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            spanText.setSpan(new ForegroundColorSpan(color), realStart, realStart + str.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
            remainString = remainString.substring(remainString.indexOf(str) + str.length());
            realStart += str.length();
        }

        return spanText;
    }

    /**
     * 给特定格式文本着色并添加点击事件
     *
     * @param source  源文本
     * @param pattern 格式
     * @param color   颜色
     * @return SpannableString
     */
    private SpannableString colorTextAndClickableWithPattern(SpannableString source, String pattern, int color, Context context) {
        if (source == null) {
            return new SpannableString("");
        }
        SpannableString spanText = source;
        List<String> patternResult = StringUtils.divideString(source.toString(), pattern);
        String remainString = source.toString();
        int realStart = 0;
        for (String str : patternResult) {
            realStart += remainString.indexOf(str);
            spanText.setSpan(new ClickSpan(context), realStart, realStart + str.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            spanText.setSpan(new ForegroundColorSpan(color), realStart, realStart + str.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
            remainString = remainString.substring(remainString.indexOf(str) + str.length());
            realStart += str.length();
        }

        return spanText;
    }

    private static class ClickSpan extends ClickableSpan {

        private Context context;

        public ClickSpan(Context context) {
            this.context = context;
        }

        @Override
        public void onClick(View widget) {
            try {
                TextView tv = (TextView) widget;
                String s = tv.getText().subSequence(tv.getSelectionStart(),
                        tv.getSelectionEnd()).toString().replace("#", "");
                if (s.startsWith("@")) {
                    HomePageActivity.startHomePageActivity(context, 0, s.substring(1));
                } else {
                    TopicListActivity.startTopicActivity(context, s);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public void updateDrawState(TextPaint ds) {
            ds.setColor(ds.linkColor);
            ds.setUnderlineText(false);    //去除超链接的下划线
        }
    }
}
